package com.letv.whatslive.mongo.dao;

import com.google.common.collect.Lists;
import com.letv.whatslive.common.utils.ObjectUtils;
import com.letv.whatslive.model.AppInfo;
import com.letv.whatslive.model.GlobalResource;
import com.letv.whatslive.model.convert.AppInfoConvert;
import com.letv.whatslive.model.convert.GlobalResourceConvert;
import com.letv.whatslive.model.utils.ObjUtils;
import com.letv.whatslive.mongo.BaseDAO;
import com.mongodb.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

//2016.1.6

/**
 * 渠道操作DAO
 * Created by shenyue on 2016/1/6.
 */
@Repository
public class AppInfoDAO extends BaseDAO {
    protected String collectionName = "appinfo";

    private static final Logger logger = LoggerFactory.getLogger(AppInfoDAO.class);

    @Override
    protected void init() {
        super.init(this.collectionName);
    }

    @Override
    protected long getAutoIncrementId() {
        return idGenerate.generateId(this.collectionName);
    }

    public Long saveOrUpdate(AppInfo appInfo) {
        DBObject query = new BasicDBObject("_id", appInfo.getId());
        DBObject dbo = this.dbCollection.findOne(query);
        if (dbo == null) {
            if(appInfo.getId()==null)
                appInfo.setId(getAutoIncrementId());
            dbo = AppInfoConvert.castAppInfoToDBObject(appInfo);
            if (dbo != null) {
                this.dbCollection.save(dbo);
                return ObjUtils.toLong(dbo.get("_id"));
            }
        } else {
            DBObject update = new BasicDBObject();
            if(StringUtils.isNotBlank(appInfo.getName())){
                update.put("name",appInfo.getName());
            }
            if(StringUtils.isNotBlank(appInfo.getDescribe())){
                update.put("describe",appInfo.getDescribe());
            }
            if(StringUtils.isNotBlank(appInfo.getDownLoadUrl())){
                update.put("downLoadUrl",appInfo.getDownLoadUrl());
            }
            if(StringUtils.isNotBlank(appInfo.getIconUrl())){
                update.put("iconUrl",appInfo.getIconUrl());
            }
            if(appInfo.getDeviceType()!=null){
                update.put("deviceType",appInfo.getDeviceType());
            }
            if(appInfo.getPriority()!=null){
                update.put("priority",appInfo.getPriority());
            }
            if(appInfo.getIsOpen()!=null){
                update.put("isOpen",appInfo.getIsOpen());
            }
            this.dbCollection.update(query, new BasicDBObject("$set", update), false, false);
            return appInfo.getId();
        }

        return 0L;
    }

    /**
     * 根据查询条件查询所有的渠道列表
     * @param params
     * @param start
     * @param limit
     * @return
     */
    public List<AppInfo> getAppInfoListByParams(Map<String, Object> params, Integer start, Integer limit) {
        List<AppInfo> result = Lists.newArrayList();
        if (limit == null) {
            limit = DEFAULT_NUM;
        }
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject query = getBasicDBObjectByParams(params);
            Integer skip = start == null ? 0 : start;
            DBCursor cur = this.dbCollection.find(query).skip(skip).limit(limit);//按照视频类型和创建时间倒序
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                AppInfo appInfo = AppInfoConvert.castDBObjectToAppInfo(dbObject);
                result.add(appInfo);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 根据查询条件Map获取查询条件对象
     * @param params
     * @return
     */
    private BasicDBObject getBasicDBObjectByParams(Map params){
        //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
        BasicDBObject query = new BasicDBObject();// 新建查询基类对象 dbo
        if (params != null && params.size() > 0) {
            if (params.get("_id") != null) {
                query.put("_id", ObjectUtils.toLong(params.get("_id")));
            }
            if (params.get("deviceType") != null) {
                query.put("deviceType", ObjectUtils.toInteger(params.get("deviceType")));
            }
            if (params.get("priority") != null) {
                query.put("priority", ObjectUtils.toInteger(params.get("priority")));
            }
//            if (params.get("name") != null) {
//                query.put("name", ObjectUtils.toString(params.get("name")));
//            }
            if (params.get("name") != null) {
                BasicDBList values = new BasicDBList();
                Pattern pattern = Pattern.compile("^.*" + params.get("name") + ".*$", Pattern.CASE_INSENSITIVE);
                values.add(new BasicDBObject("_id", ObjectUtils.toLong(params.get("name"))));
                values.add(new BasicDBObject("name", pattern));
                query.put("$or", values);
            }
            if (params.get("describe") != null) {
                query.put("describe", ObjectUtils.toString(params.get("describe")));
            }
            if (params.get("downLoadUrl") != null) {
                query.put("downLoadUrl", ObjectUtils.toString(params.get("downLoadUrl")));
            }
            if (params.get("iconUrl") != null) {
                query.put("iconUrl", ObjectUtils.toString(params.get("iconUrl")));
            }

            if (params.get("isOpen") != null) {
                query.put("isOpen", ObjectUtils.toInteger(params.get("isOpen")));
            }
        }

        return query;
    }


    /**
     * 根据条件获取相应的渠道列表
     * @param params
     * @return
     */
    public List<AppInfo> getAllAppInfoByParams(Map<String, Object> params, Map<String, Object> orders){
        List<AppInfo> result = Lists.newArrayList();
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject order = getOrderParams(orders);
            BasicDBObject query = getBasicDBObjectByParams(params);
            DBCursor cur = this.dbCollection.find(query).sort(order);
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                AppInfo appInfo = AppInfoConvert.castDBObjectToAppInfo(dbObject);
                result.add(appInfo);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 根据设备Id获取渠道
     * @param id
     * @return
     */
    public AppInfo getAppInfoById(Long id) {
        BasicDBObject query = new BasicDBObject();
        AppInfo appInfo = new AppInfo();
        query.put("_id", id);
        DBObject dbObject = this.dbCollection.findOne(query);
        if (dbObject == null) return null;
        try {
            appInfo = AppInfoConvert.castDBObjectToAppInfo(dbObject);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return appInfo;
    }

    public AppInfo saveAppInfo(AppInfo appInfo) {
        try {
            appInfo.setId(getAutoIncrementId());
            DBObject dbo = AppInfoConvert.castAppInfoToDBObject(appInfo);
            WriteResult wr = this.dbCollection.insert(dbo);
            return appInfo;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
    }

    public Long countAppInfoByParams(Map params) {
        //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
        BasicDBObject query = getBasicDBObjectByParams(params);
        return this.dbCollection.count(query);
    }

    public void updateAppInfo(AppInfo appInfo) {
        DBObject queryCondition = new BasicDBObject();
        queryCondition.put("_id", appInfo.getId());
        BasicDBObject setValue = (BasicDBObject)AppInfoConvert.castAppInfoToDBObject(appInfo);
        //剔除主键修改
        if (setValue.containsField("_id")) {
            setValue.removeField("_id");
        }
        DBObject values = new BasicDBObject("$set", setValue);
        this.dbCollection.update(queryCondition, values, false, false);
    }

    public long insertAppInfo(AppInfo appInfo){
        DBObject obj = AppInfoConvert.castAppInfoToDBObject(appInfo);
        return this.insert(obj);
    }

    private BasicDBObject getOrderParams(Map<String, Object> orders) {
        BasicDBObject order = new BasicDBObject();
        if(null != orders &&orders.size()>0){
            for(String key : orders.keySet()){
                order.append(key, Integer.valueOf(String.valueOf(orders.get(key))));
            }
        }else{
            //默认按照id倒序排序
            order.append("_id", -1);
        }
        return order;
    }

    public List<AppInfo> getAppInfoListByParams(Map<String, Object> params, Map<String, Object> orders, Integer start, Integer limit) {

        List<AppInfo> result = Lists.newArrayList();
        if (limit == null) {
            limit = DEFAULT_NUM;
        }
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject order = getOrderParams(orders);
            BasicDBObject query = getBasicDBObjectByParams(params);
            Integer skip = start == null ? 0 : start;
            DBCursor cur = this.dbCollection.find(query).skip(skip).sort(order).limit(limit);//按createTime的值倒叙排列
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                AppInfo appInfo = AppInfoConvert.castDBObjectToAppInfo(dbObject);
                result.add(appInfo);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return result;
    }

    public void deleteAppInfoByParams(Long id){
        BasicDBObject query = new BasicDBObject();
        query.put("_id", id);
        this.dbCollection.remove(query);
    }
}